package com.good.cm.controller;

import com.good.cm.exception.ParamsException;
import com.good.cm.model.ResultInfo;
import com.good.cm.model.UserModel;
import com.good.cm.service.UserService;
import com.good.cm.utils.CookieUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登录接口
     * @param userModel
     * @param response
     * @return
     */
    @PostMapping("user/login")
    @ResponseBody
    public ResultInfo login(@RequestBody UserModel userModel, HttpServletResponse response){
        //String userName,String pwd
        //“Ctrl+Alt+T” try catch快捷键
        System.out.println("用户名："+userModel.getUsername());
        System.out.println("密码："+userModel.getPassword());
        ResultInfo res=new ResultInfo();
        res.setCode(200);
        UserModel um= null;
        try {
            um = userService.login(userModel.getUsername(),userModel.getPassword());
            CookieUtil.addCookie(response,"userId",um.getId());
        } catch (ParamsException e) {
            e.printStackTrace();
            res.setCode(520);
            res.setMsg(e.getMessage().toString());
        }
        catch (Exception e) {
            e.printStackTrace();
            res.setCode(500);
            res.setMsg(e.getMessage().toString());
        }
        res.setResult(um);
        return res;
    }


    @PostMapping("user/login02")
    @ResponseBody
    public ResultInfo login02(@RequestBody UserModel userModel, HttpServletResponse response){
        ResultInfo res=new ResultInfo();
        res.setCode(200);
        UserModel um= null;
         um = userService.login(userModel.getUsername(),userModel.getPassword());
        CookieUtil.addCookie(response,"userId",um.getId());
        res.setResult(um);
        return res;
    }

    /**
     * 修改密码接口
     * @param userModel
     * @return
     */
    @PostMapping("user/updatePassword")
    @ResponseBody
    public ResultInfo updatePassword(@RequestBody UserModel userModel){
        System.out.println("开始修改密码");
        ResultInfo res=new ResultInfo();
        res.setCode(200);
        UserModel um= null;//caa30835-fac8-4af5-a5e9-954376341a7a
        try {
            userService.updatePassword(userModel.getId(),userModel.getPassword(),userModel.getNewPwd(),userModel.getNewConfigPwd());
        } catch (Exception e) {
            res.setMsg(e.getMessage());
            res.setCode(500);
        }
        return  res;
    }



}
